//
//  Button+Extension.swift
//  XS微博
//
//  Created by 王小帅 on 2016/11/13.
//  Copyright © 2016年 王小帅. All rights reserved.
//

import UIKit
/// 自定义button
class titleButton:UIButton {

    init(title: String?) {
        super.init(frame: CGRect())
        
        if title == nil {
            setTitle("首页", for: .normal)
            
        }else{
            setTitle(title! + " ", for: .normal)
            setImage(UIImage(named:"compose_guide_check_box_right"), for: .normal)
            setImage(UIImage(named:"compose_guide_check_box_default"), for: .selected)
        }
        
        titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        setTitleColor(UIColor.darkGray, for: [])
        // ****** 注意 这里要给每个uiview设置sizetofit 否则第一次显示位置错误******
        titleLabel?.sizeToFit()
        imageView?.sizeToFit()
        // 设置button的sizeToFit 否则它不知道要如何显示
        sizeToFit()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    /// 重写布局方法  让图片在文字的后面
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 判断是否有图标和标题
        guard let imageView = imageView, let titleLabel = titleLabel else {
            return
        }
        // 对应移动
        titleLabel.frame = titleLabel.frame.offsetBy(dx: -imageView.bounds.width, dy: 0)
        imageView.frame = imageView.frame.offsetBy(dx: titleLabel.bounds.width, dy: 0)
    }
}


/// 用于给button扩展方法
extension UIButton {

    convenience init(title:String,imgNormal:String,imgHight:String,titleColorNor:UIColor,titleColorHight:UIColor){
    
        self.init()
        self.setTitle(title, for: .normal)
        self.setBackgroundImage(UIImage(named: imgNormal), for: .normal)
        self.setBackgroundImage(UIImage(named: imgHight), for: .highlighted)
        self.setTitleColor(titleColorNor, for: .normal)
        self.setTitleColor(titleColorHight, for: .highlighted)
    }
}

